import {Component} from '@angular/core';
import {
  NavController,
  NavParams,
  ModalController,
  Events,
  LoadingController,
  Platform,
  ViewController
} from 'ionic-angular';
import {ChatDetailPage} from '../chat-detail/chat-detail'
import {
  baseCommon
} from '../../common/baseCommon';
import {
  AppConfig
} from './../../app/app.config';
import {
  Storage
} from '@ionic/storage'
import {
  Http,
  Headers,
  RequestOptions
} from '@angular/http';

// import * as rongCloud from '../../assets/js/RongIMLib.js';
/**
 * Generated class for the MessagePage page.
 *
 * See https://ionicframework.com/docs/components/#navigation for more info on
 * Ionic pages and navigation.
 */

@Component({
  selector: 'page-message',
  templateUrl: 'message.html',
})
export class MessagePage{

  groupList = [];
  ifSuccess: boolean = false;
  phone: any;
  token: string = '';
  groupID: any;
  sessionID: any;
  currentUser: any;
  messageList: any;
  groupListCopy = [];

  constructor(
    public navCtrl: NavController,
    public navParams: NavParams,
    public modalCtrl: ModalController,
    public event: Events,
    public http: Http,
    public storage: Storage,
    public loadingCtrl: LoadingController) {
  }

  ionViewDidLoad() {
    console.log('message页面初始化')
    //听取消息的订阅
    this.event.subscribe('message.received', (mes, time) => {
      if (AppConfig.currentPage == mes.groupID) {
        this.event.publish('chat.received', mes, Date.now());
        return;
      } else {
        this.insert(mes);
        this.groupList.forEach(el => {
          if (el.id == mes.groupID) {
            el.getnum = el.getnum + 1;
            return;
          }
        });
      }
      // })
    })

    this.storage.get('sessionID').then(val => {
      this.sessionID = val;
      this.storage.get('groups').then(val => {
        if (val == null || val.length == 0) {
          this.getJoinedGroup(AppConfig.httpLoc + '/group/groups?sessionID=' + this.sessionID);
        } else {
          AppConfig.groups = val;
          this.groupList = AppConfig.groups;
        }
      });
    });

    this.storage.get('phone').then(val => {
      this.currentUser = val;
    })
  }

  ionViewWillEnter() {
    this.event.unsubscribe('chat.received');    //对取消订阅行为进行补充，保障取消订阅行为稳定性
    if (AppConfig.groups != null)
      this.groupList = AppConfig.groups;    //使用AppConfig的groups
  }

  /**
   * 转到聊天页面
   *
   * @param {any} id
   * @param {any} name
   * @memberof MessagePage
   */
  chatDetail(id, name) {
    let model = this.modalCtrl.create(ChatDetailPage, {'groupID': id, 'groupName': name});
    model.onDidDismiss(data => {
      AppConfig.currentPage = -1;
      this.groupList.forEach(el => {
        if (el.id == data) {
          el.getnum = 0;
          return;
        }
      });
      this.event.unsubscribe('chat.received');
      AppConfig.viewCtrl = null;
    });
    model.present();
  }


  /**
   * 得到已加入的圈子
   *
   * @param {any} apiUrl
   * @memberof GroupPage
   */
  getJoinedGroup(apiUrl) {
    let headers = new Headers({
      'Content-Type': 'application/x-www-form-urlencoded',
    });

    let options = new RequestOptions({
      headers: headers,
    });

    this.http.get(apiUrl, options)
      .toPromise()
      .then(data => {
        this.groupList = data.json().data;
        // AppConfig.groups = this.groupList;      //将groupList设置到全局
        console.log(this.groupList)
        this.groupList.forEach(element => {
          element.getnum = 0;
          element.status = 0;
        });
        this.ifSuccess = true;
        this.getMessageRes(AppConfig.httpLoc + '/chat/message?sessionID=' + this.sessionID);
        AppConfig.groups = this.groupList;    //配置全局GroupList
        this.storage.set('groups', AppConfig.groups);
      }, err => {
        console.log(err);
      })
  }

  /**
   * 请求离线消息
   *
   * @param {any} apiUrl
   * @memberof MessagePage
   */
  getMessageRes(apiUrl) {
    let headers = new Headers({
      'Content-Type': 'application/x-www-form-urlencoded',
    });

    let options = new RequestOptions({
      headers: headers,
    });

    this.http.get(apiUrl, options)
      .toPromise()
      .then(data => {
        this.messageList = data.json().data;
        this.messageList.forEach(sl => {
          sl.date = sl.date.split("T")[0] + " " + sl.date.split("T")[1].split(".")[0];
          this.insert(sl);
          this.groupList.forEach(el => {
            if (el.id == sl.groupID) {
              el.getnum++;
            }
          });
        });
      }, err => {
        console.log(err);
      })
  }

  insert(value) {
    AppConfig.db.message.add(value).then(function () {
      console.log('数据插入成功');
    })
  }

  getItems(ev: any) {
    this.groupList = AppConfig.groups;
    let val = ev.target.value;
    if (val && val.trim() != '') {
      this.groupList = this.groupList.filter((item) => {
        return ((String)(item.name).toLowerCase().indexOf(val.toLowerCase()) > -1);
      })
    }
  }

}
